/**
 * OSAmI: Open Source Ambient Intelligence
 * Servlets running on the gateway, for displaying data from the sensor nodes.
 * Copyright (C) Jonathan Ferreira 2010 (internship in LCIS-INPG, for a demo in the FR part of the OSAMI project)
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
 */
package org.osami.gateway.display.internal;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.gateway.identity.Identity;
import org.osami.gateway.identity.IdentityProvider;
import org.osami.gateway.sensor.data.SenseData;
import org.osami.gateway.storage.ISenseDataStorage;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;

@Component
@Instantiate
public class SensorsViewServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Requires
    private ISenseDataStorage storage;

    @Requires
    private HttpContext context;

    @Requires
    private HttpService httpService;

    @Requires(optional = true)
    private IdentityProvider identityProvider;

    private final DateFormat df = new SimpleDateFormat("yyyy/MM/dd'&nbsp;&nbsp;'HH:mm:ss:SSS z");

    @Validate
    public void start() throws ServletException, NamespaceException {
        this.httpService.registerServlet(ServletPaths.SENSORS, this, null, this.context);
    }

    @Invalidate
    public void stop() {
        this.httpService.unregister(ServletPaths.SENSORS);
    }

    private void doGetPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();

        writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
        writer.println("<html lang=\"en\">");

        // HTML Head
        // ---------------------------------------------------
        writer.println("<head>");
        writer.println("<title>Sensor data at " + new Date() + "</title>");
        writer.println("<link href=\"/resource/css/designSensor.css\" rel=\"stylesheet\" type=\"text/css\" />");
        writer.println("<meta http-equiv=\"refresh\" content=\"5\">");
        writer.println("</head>");

        // HTML Body
        // ---------------------------------------------------
        writer.println("<body>");

        writer.println("<H1>List of all sensors</H1><hr/>");

        printAlarmTable(writer);

        writer.println("<hr/>");
        writer.println("<a href=\"" + ServletPaths.INDEX + "\">Go back to main page</a>\n");
        writer.println("</body>");
        writer.println("</html>");
    }

    @Override
    synchronized protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        doGetPost(req, resp);
    }

    @Override
    synchronized protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        doGetPost(req, resp);
    }

    private void printAlarmTable(PrintWriter writer) {
        writer.println("<br/><br/>");
        writer.println("<table>");
        // Print table headers
        writer.println("<thead><tr>");
        // Print each column name here
        printAlarmTableHeaders(writer);
        writer.println("</tr></thead>");

        // Print table body
        writer.println("<tbody>");
        // Print each alarm in its own row
        Map<String, SenseData> sensors = new TreeMap<String, SenseData>();
        synchronized (this.storage) {
            for (SenseData sd : this.storage) {
                String senseId = sd.getSenseId();
                sensors.put(senseId, sd);
            }

            for (SenseData sd : sensors.values()) {
                printSenseDataRow(writer, sd);
            }
        }

        writer.println("</tbody>");
        writer.println("</table>");
    }

    private void printAlarmTableHeaders(PrintWriter writer) {
        writer.println("<th>SenseId</th>");
        writer.println("<th>Type</th>");
        writer.println("<th>Value</th>");
        writer.println("<th>Unit</th>");
        writer.println("<th>Time</th>");
    }

    private void printSenseDataRow(PrintWriter writer, SenseData sd) {
        writer.println("<tr>");

        String senseId = sd.getSenseId();
        String [] t = senseId.split("/");
        if (t.length != 0) {
            String nodeId = t[0];
            String type;
            if (t.length >= 2) {
                type = t[1];
            }
            else {
                type = nodeId;
            }

            String identityName = "";
            Identity identity = this.identityProvider.getBoundIdentity(nodeId);
            if (identity != null) {
                final String identityName2 = identity.getName();
                if (identityName2 != null && !identityName2.equals("")) {
                    identityName = identityName2;
                }
            }

            if (!identityName.equals("")) {
                printTableCell(writer, "<a href=\"" + ServletPaths.SENSOR + "/" + nodeId + "/" + type + "\" >" + identityName + "/" + type + "</a>");
            }
            else {
                printTableCell(writer, "<a href=\"" + ServletPaths.SENSOR + "/" + senseId + "\" >" + senseId + "</a>");
            }

            printTableCell(writer, sd.getType());
            printTableCell(writer, sd.getValue().toString());
            printTableCell(writer, sd.getUnit());

            Date date = new Date(sd.getTimeStamp());
            StringBuffer sb = this.df.format(date, new StringBuffer(), new FieldPosition(DateFormat.FULL));
            printTableCell(writer, sb.toString());

        }
        writer.println("</tr>");
    }

    private void printTableCell(PrintWriter writer, String content) {
        writer.println("<td>" + content + "</td>");
    }

}
